<template>
  <div class="app-container">
    <div class="search-box">
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="60px" class="search-form-new">
        <el-form-item label="订单编号" label-width="68px" prop="no">
          <el-input v-model="queryParams.no" placeholder="请输入订单编号" clearable />
        </el-form-item>

        <el-form-item label="游戏" prop="gameId">
          <el-select style="width: 100%;" filterable clearable v-model="queryParams.gameId" placeholder="请选择游戏名称">
            <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="queryParams.account" placeholder="请输入账号" clearable />
        </el-form-item>

        <el-form-item label="租号人" prop="useUserId">
          <virtual-select @change="sellerChange" v-model="queryParams.useUserId" :list="userList" label="nickName"
            value="userId" :placeholder="'输入关键字用于租号人'" :keeps-params="20" :is-concat="false" :concat-symbol="' || '"
            :is-multiple="false" :disabled="false" :allow-create="false" />
        </el-form-item>
        <!-- <el-form-item label="订单状态" label-width="68px" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
            <el-option label="待支付" value="1"></el-option>
            <el-option label="出租中" value="2"></el-option>
            <el-option label="已完成" value="3"></el-option>
            <el-option label="已取消" value="4"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="创建人" prop="userId">
          <el-select v-model="queryParams.createId" placeholder="请选择创建人" clearable filterable>
            <el-option v-for="staff in staffList" :key="staff.userId" :label="staff.userName" :value="staff.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" label-width="68px">
          <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
            value-format="yyyy-MM-dd" format="yyyy-MM-dd" :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" type="warning" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="zdy-main customTab customTabNew" style="padding: 0;">
      <div class="tabs flex alc">
        <el-radio-group v-model="actived" @change="tabChange">
          <el-radio-button :label="tab.value" v-for="tab in orderStatusArr" :key="tab.value">{{ tab.name
            }}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="table_box table_box_new table-section">
      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="orderList" border style="width: 100%">
        <el-table-column prop="no" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="gameName" label="游戏" width="120"></el-table-column>
        <el-table-column prop="account" label="账号" width="150"></el-table-column>
        <el-table-column prop="rentUserName" label="出租人" width="120"></el-table-column>
        <el-table-column prop="useUserName" label="租号人" width="120"></el-table-column>
        <el-table-column prop="rentLength" label="租号时长" width="100"></el-table-column>
        <el-table-column prop="priceSub" label="预付款" width="100"></el-table-column>
        <el-table-column prop="priceRent" label="租金" width="100"></el-table-column>
        <!-- <el-table-column prop="priceServer" label="手续费" width="100"></el-table-column> -->
        <el-table-column prop="priceTotal" label="总金额" width="100"></el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.orderStatus == 1">待支付</el-tag>
            <el-tag type="warning" v-else-if="scope.row.orderStatus == 2">出租中</el-tag>
            <el-tag type="success" v-else-if="scope.row.orderStatus == 3">已完成</el-tag>
            <el-tag type="info" v-else-if="scope.row.orderStatus == 4">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payStatus" label="支付状态" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.payStatus == 1">待支付</el-tag>
            <el-tag type="success" v-else-if="scope.row.payStatus == 2">已支付</el-tag>
            <el-tag type="info" v-else-if="scope.row.payStatus == 3">已退款</el-tag>
            <el-tag @click="statSync(scope.row.id)" style="cursor: pointer;" type="warning"
              v-else-if="scope.row.payStatus === 4">退款中
              <i class=" el-icon-refresh" style="font-size: 14px;"></i>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
        <el-table-column prop="createName" label="创建人" width="120"></el-table-column>
        <el-table-column prop="payTime" label="支付时间" width="160"></el-table-column>
        <el-table-column prop="finishTime" label="完成时间" width="160"></el-table-column>
        <el-table-column prop="cancelReason" label="取消原因" width="100"></el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template slot-scope="scope">
            <el-button type="add" @click="handleView(scope.row)">
              查看
            </el-button>
            <!-- 待付款状态操作 -->
            <template v-if="scope.row.orderStatus == 1">
              <el-button type="text" @click="handleChangeToRenting(scope.row)" v-if="checkPermi(['rental:order-to'])">
                转出租中
              </el-button>
              <el-button v-if="checkPermi(['rental:order-cancle'])" type="del" @click="handleCancelOrder(scope.row)">
                取消订单
              </el-button>
            </template>
            <!-- 出租中状态操作 -->
            <template v-else-if="scope.row.orderStatus == 2">
              <el-button type="add" @click="handleChangePayStatus(scope.row)"
                v-if="scope.row.sourceScene == 2 && checkPermi(['rental:order-pay'])">
                修改支付状态
              </el-button>
              <el-button type="text" @click="handleCompleteOrder(scope.row)">
                完成订单
              </el-button>
              <el-button type="del" @click="handleCancelOrder(scope.row)">
                取消订单
              </el-button>
            </template>
            <el-button type="text" v-if="checkPermi(['interOrder:group']) && !scope.row.groupId && !scope.row.toGroup"
              @click="oneClickGroup(scope.row)">一键拉群</el-button>
            <el-button type="del"
              v-if="checkPermi(['interOrder:dismissGroup']) && scope.row.groupId && scope.row.toGroup"
              @click="cancelGroupIM(scope.row.id)">解散群组</el-button>
            <el-button type="text"
              v-if="checkPermi(['interOrder:recoverGroup']) && scope.row.groupId && !scope.row.toGroup"
              @click="recoveryGroup(scope.row.id)">恢复群组</el-button>
            <el-button type="text"
              v-if="checkPermi(['interOrder:enterGroup']) && scope.row.groupId && scope.row.toGroup"
              @click="enterGroup(scope.row)">进入群聊</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 完成订单弹窗 -->
    <el-dialog title="完成订单" :visible.sync="completeDialogVisible" width="800px">
      <!-- 订单信息展示 -->
      <el-descriptions title="订单信息" :column="3" border>
        <el-descriptions-item :span="3" label="订单编号">{{ currentOrder.no }}</el-descriptions-item>
        <el-descriptions-item label="游戏">{{ currentOrder.gameName }}</el-descriptions-item>
        <el-descriptions-item label="账号">{{ currentOrder.account }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag v-if="currentOrder.orderStatus == 1">待支付</el-tag>
          <el-tag type="warning" v-else-if="currentOrder.orderStatus == 2">出租中</el-tag>
          <el-tag type="success" v-else-if="currentOrder.orderStatus == 3">已完成</el-tag>
          <el-tag type="info" v-else-if="currentOrder.orderStatus == 4">已取消</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <el-tag v-if="currentOrder.payStatus == 1">未支付</el-tag>
          <el-tag type="success" v-else-if="currentOrder.payStatus == 2">已支付</el-tag>
          <el-tag type="info" v-else-if="currentOrder.payStatus == 3">已退款</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ currentOrder.createName }}</el-descriptions-item>

        <el-descriptions-item label="租号时长">{{ currentOrder.rentLength }}小时</el-descriptions-item>
        <el-descriptions-item label="出租人">{{ currentOrder.rentUserName }}</el-descriptions-item>
        <el-descriptions-item label="租号人">{{ currentOrder.useUserName }}</el-descriptions-item>
        <el-descriptions-item label="预付款"><span style="color:red">¥{{ currentOrder.priceSub
            }}</span></el-descriptions-item>
        <el-descriptions-item v-if="currentOrder.priceServer" label="服务费"><span style="color:red">¥{{
          currentOrder.priceServer }}</span></el-descriptions-item>
        <el-descriptions-item label="租金"><span style="color:red">¥{{ currentOrder.priceRent
            }}</span></el-descriptions-item>
        <el-descriptions-item label="总金额"><span style="color:red">¥{{ currentOrder.priceTotal
            }}</span></el-descriptions-item>
      </el-descriptions>
      <!-- 填写信息 -->
      <el-form ref="completeForm" :model="completeForm" :rules="completeRules" style="margin-top: 20px;">
        <el-form-item label="退款金额" prop="priceBack">
          <el-input-number :precision="1" :step="0.1" v-model="completeForm.priceBack" :min="0"
            :max="Math.max(0, currentOrder.priceTotal - completeForm.priceServer)" controls-position="right"
            @change="calculateSettlement">
          </el-input-number>
        </el-form-item>
      </el-form>
      <el-descriptions title="结算信息" :column="4" :labelStyle="{ width: '95px' }" border>
        <el-descriptions-item label="服务费">{{ completeForm.priceServer }}</el-descriptions-item>
        <el-descriptions-item :labelStyle="{ width: '110px' }" label="号主结算金额">{{ completeForm.ownerSettlement
          }}</el-descriptions-item>
        <el-descriptions-item label="租号人退款">{{ completeForm.priceBack }}</el-descriptions-item>
      </el-descriptions>
      <div class="task-info-section">
        <div class="task-info-desc">
          <p>* 结算和退款金额请自行处理，系统不自动处理；</p>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="completeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCompleteOrder">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改支付状态弹窗 -->
    <el-dialog title="修改支付状态" :visible.sync="payStatusDialogVisible" width="500px">
      <el-form ref="payStatusForm" :model="payStatusForm" :rules="payStatusRules" label-width="100px">
        <el-form-item label="支付状态" prop="payStatus">
          <el-select v-model="payStatusForm.payStatus" placeholder="请选择支付状态" style="width: 100%;">
            <el-option label="未支付" :value="1"></el-option>
            <el-option label="已支付" :value="2"></el-option>
            <el-option label="已退款" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payStatusDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPayStatusChange">确 定</el-button>
      </div>
    </el-dialog>
    <rentalOrderDetails ref="rentalOrderDetailRef"></rentalOrderDetails>
  </div>
</template>

<script>
import VirtualSelect from "@/components/VirtualSelect.vue";
import supplyConfigApi from "@/api/system/supplyConfig";

import { rentalOrderlist, rentalOrderDetail, rentalOrderPay, rentalOrderPull, rentalOrderCancel, rentalOrderRecover, rentalOrderRenting, rentalCancel, rentalComplete, rentalRefund } from "@/api/rental/account.js";

import Pagination from "@/components/Pagination";

import customerServiceApi from "@/api/pickUp/customerService";

import rentalOrderDetails from "@/views/rental/components/rentalOrderDetail.vue";
export default {
  // name: "RentalOrder",
  components: { Pagination, VirtualSelect, rentalOrderDetails },

  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],

      // 用户列表
      userList: [],

      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: '',
        gameId: '',
        account: '',
        userId: '',
        useUserId: '',
        status: '',
        createId: '',
        beginTime: '',
        orderStatus: '',
        endTime: ''
      },
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 当前选中订单
      currentOrder: {},
      // 完成订单表单
      completeForm: {
        orderId: null,
        priceBack: 0,
        priceServer: 0,
        ownerSettlement: 0
      },
      // 表单校验
      completeRules: {
        priceBack: [{ required: true, message: "请输入退款金额", trigger: "blur" }]
      },
      payStatusForm: {
        id: '',
        payStatus: ''
      },
      payStatusRules: {
        payStatus: [{ required: true, message: "请选择支付状态", trigger: "change" }]
      },
      // 弹窗显示控制
      completeDialogVisible: false,
      payStatusDialogVisible: false,
      staffList: [],

      serviceFeeConfig: {
        rentalServiceFee: "",
        rentalMinNum: 0,
      },
      actived: '',
      orderStatusArr: [
        { name: '全部', value: '' },
        { name: '待支付', value: 1 },
        { name: '出租中', value: 2 },
        { name: '已完成', value: 3 },
        { name: '已取消', value: 4 },
      ]
    };
  },
  computed: {

    shopInfo() {
      return this.$store.getters.shopInfo;
    },
    allGameList() {
      return this.$store.getters.allGameList;
    },
  },
  created() {
    this.getUserList()
    this.getStaffList()
    this.getList();
  },
  methods: {
    tabChange() {
      this.queryParams.pageNum = 1;
      this.queryParams.orderStatus = this.actived;
      this.getList();
    },
    /** 查询用户列表 */
    getUserList() {
      supplyConfigApi.getAllUserList().then((res) => {
        this.userList = res.rows || [];
      });
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0] + ' ' + '00:00:00';
        this.queryParams.endTime = this.dateRange[1] + ' ' + '23:59:59';
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }

      rentalOrderlist(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    sellerChange(val) {
      const user = this.userList.find(item => item.userId == val);
      if (user) {
        this.queryParams.useUserId = user.userId;
      }
    },

    /** 查询员工列表 */
    getStaffList() {
      supplyConfigApi.getAllUserList({ userNewType: 1 }).then(res => {
        this.staffList = res.rows || [];
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    /** 查看订单详情 */
    async handleView(row) {
      try {
        const res = await rentalOrderDetail(row.id)
        this.$nextTick(() => {
          this.$refs.rentalOrderDetailRef.init(res.data)
        })
        // this.currentOrder = res.data
        // this.viewDialogVisible = true;
      } catch (error) {
        this.$modal.msgError(error.message)
      }
    },
    /** 转出租中 */
    handleChangeToRenting(row) {
      let cont = `确认要将订单${row.no}转为出租中状态吗？`
      this.$modal.confirm(cont).then(() => {
        return rentalOrderRenting(row.id);
      }).then(() => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      }).catch(() => { });
    },
    /** 取消订单 */
    handleCancelOrder(row) {
      console.log(row.sourceScene, row.payStatus)
      let cont = `请输入取消原因？<br/>`
      if (row.sourceScene == 1 && row.payStatus == 2) {
        cont = `请输入取消原因？<br/>取消后,订单金额将原路退回租号人`
      }
      this.$prompt(cont, '取消订单', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '请填写取消原因';
          }
          return true;
        },
      }).then(({ value }) => {
        rentalCancel({
          id: row.id,
          cancelReason: value
        }).then(() => {
          this.$message.success('取消成功');
          this.getList();
        })
      }).catch(() => {
        // 用户取消操作
        this.$message.info('已取消操作');
      });
    },
    /** 修改支付状态 */
    handleChangePayStatus(row) {
      this.payStatusForm.id = row.id;
      this.payStatusForm.payStatus = row.payStatus;
      this.payStatusDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.payStatusForm.resetFields();
      });
    },
    /** 提交支付状态修改 */
    submitPayStatusChange() {
      this.$refs.payStatusForm.validate(valid => {
        if (valid) {
          const params = {
            id: this.payStatusForm.id,
            payStatus: this.payStatusForm.payStatus
          };
          rentalOrderPay(params).then(response => {
            this.$modal.msgSuccess("支付状态修改成功");
            this.payStatusDialogVisible = false;
            this.getList();
          }).catch(error => {
            this.$modal.msgError(error.message || "修改失败");
          });
        }
      });
    },
    async getFuwu() {
      const res = await customerServiceApi.getConfigByTenantId({
        configKey: "accountRental",
        tenantId: this.shopInfo.tenantId
      })
      return res
    },
    /** 完成订单 */
    async handleCompleteOrder(row) {
      const res = await this.getFuwu()
      if(res.data.configValue) {
        this.serviceFeeConfig = JSON.parse(res.data.configValue)
      }
      
      //计算服务费 
      this.currentOrder = row;
      this.completeForm.orderId = row.id;
      this.completeForm.priceBack = 0;
      this.completeForm.priceServer = 0;
      this.completeForm.ownerSettlement = 0;
      this.completeDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.completeForm.resetFields();
      });
      if(res.data.configValue) {
         const priceServer = (Math.round(this.currentOrder.priceTotal) - Math.round(this.completeForm.priceBack)) * (this.serviceFeeConfig.rentalServiceFee / 100)
          if (priceServer < this.serviceFeeConfig.rentalMinNum) {
            this.completeForm.priceServer = Math.round(this.serviceFeeConfig.rentalMinNum * 100) / 100;
          } else {
            this.completeForm.priceServer = Math.round(priceServer * 100) / 100;
          }
      }else {
        this.completeForm.priceServer = 0
      }
     
      this.calculateSettlement()
    },
    /** 计算结算金额 */
    calculateSettlement() {
      //总金额 -  退款金额 * 服务费比率
      const priceTotal = this.currentOrder.priceTotal || 0;
     
      const priceBack = this.completeForm.priceBack || 0;
         const priceServer = (Math.round(this.currentOrder.priceTotal) - Math.round(this.completeForm.priceBack)) * (this.serviceFeeConfig.rentalServiceFee / 100)
      if (priceServer < this.serviceFeeConfig.rentalMinNum) {
        this.completeForm.priceServer = Math.round(this.serviceFeeConfig.rentalMinNum * 100) / 100;
      } else {
        this.completeForm.priceServer = Math.round(priceServer * 100) / 100;
      }
      const result = Math.round((priceTotal -  this.completeForm.priceServer - priceBack + Number.EPSILON) * 100) / 100;
      const finalResult = result.toFixed(2);
      this.completeForm.ownerSettlement = finalResult; 
      // 结算金额 = 总金额 - 服务费 - 退款金额
      // this.completeForm.ownerSettlement = parseFloat(
      //     (this.currentOrder.priceTotal - this.completeForm.priceServer - this.completeForm.priceBack).toFixed(2)
      // )
      
      // 算服务费  实付款-退款金额 x 百分比 = 服务费

     
    },
    /** 提交完成订单 */
    submitCompleteOrder() {
      this.$refs.completeForm.validate(valid => {
        if (valid) {
          const params = {
            id: this.completeForm.orderId,
            priceBack: this.completeForm.priceBack
          };
          rentalComplete(params).then(response => {
            this.$modal.msgSuccess("订单完成成功");
            this.completeDialogVisible = false;
            this.getList();
          });
        }
      });
    },
    /** 群操作 */
    oneClickGroup(row) {

      this.$confirm('确认一键拉群吗?', { type: 'warning', dangerouslyUseHTMLString: true, confirmButtonText: '确认', cancelButtonText: '取消' })
        .then(() => {
          this.laqunLoading = true
          rentalOrderPull(row.id).then(res => {
            this.$message.success('拉群成功')
            this.getList()
          }).finally(() => {
            this.laqunLoading = false
          })
        })
        .catch(() => { /* 取消 */ })
    },
    cancelGroupIM(id) {
      this.$confirm('确认解散群组？', '提示', { type: "warning" }).then(() => {
        rentalOrderCancel(id).then(res => {
          this.$message.success('已解散群组');
          this.getList()
        })

      }).catch(() => { });
    },
    async recoveryGroup(id) {
      const res = await rentalOrderRecover(id)
      if (res.code === 200) {
        this.$message.success('已恢复群组');
        this.getList()
      }
    },
    enterGroup(row) {
      if (!row.toGroup) {
        this.$message.error('未找到群聊')
        return
      }
      let obj = {
        type: "goChat",
        hxusername: row.toGroup,
        chatType: 'groupChat',
      };
      this.$store.dispatch("postMsgToIM", obj);

    },
    statSync(id) {
      rentalRefund(id).then(res => {
        this.$message.success('已同步')
        this.getList()
      })
    }
  }
};
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.order-info,
.settlement-info {
  border: 1px solid #ebeef5;
  padding: 15px;
  border-radius: 4px;
  background-color: #f9f9f9;
  margin-bottom: 20px;
}

.order-info h4,
.settlement-info h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}


.task-info-section {
  margin-top: 16px;
  background-color: #f8f9fa;

  border-radius: 4px;
  height: 40px;
  line-height: 40px;
  padding: 0 8px;
}
</style>